#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>

int my_dup(int oldfd){
    int dupFd;
    dupFd = fcntl(oldfd, F_DUPFD, 0);
    if(dupFd == -1){
        printf("Error F_DUPFD fnctl %d %s\n", oldfd, strerror(errno));
        return -1;
    }
    return dupFd;
}

int my_dup2(int oldfd, int newfd){
    int fd;
    if(oldfd == newfd)
        return newfd;
    
    if(fcntl(oldfd, F_GETFL) == -1){
        errno = EBADF;
        return -1;
    }

    close(newfd);
    fd = fcntl(oldfd, F_DUPFD, newfd);
    if(fd == -1)
        return -1;

    return fd;

}

int main(){
    int fd, fd2;
    char *str = "Test string!\n";

    fd = my_dup(STDIN_FILENO);
    if(fd == -1){
        printf("Error my_dup %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);
    }
    printf("Duplicate fd = %d\n", fd);
    if(write(fd, str, strlen(str)) == -1){
        printf("Error write fd %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);   
    }

    if(close(fd) == -1){
        printf("Error close fd %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);       
    }



    fd2 = my_dup2(STDIN_FILENO, 10);
    if(fd2 == -1){
        printf("Error my_dup2 %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);
    }
    printf("Duplicate fd2 = %d\n", fd2);

    if(write(fd2, str, strlen(str)) == -1){
        printf("Error write fd %d %s\n", fd2, strerror(errno));
        exit(EXIT_FAILURE);   
    }

    if(close(fd2) == -1){
        printf("Error close fd %d %s\n", fd, strerror(errno));
        exit(EXIT_FAILURE);       
    }

    exit(EXIT_SUCCESS);
}